package org.bugeden.netdisk.user;

import java.io.*;
import java.util.*;
public class jTaskFileStore  
{
   private String userAccount;
   public int index;
   private List<jTask> taskset;
   private jFileEditor fe;
   public jTaskFileStore(String userAccount)  throws IOException
   {   
       taskset=new LinkedList();
//       try
       {
           open(userAccount);
       } 
//       catch(IOException ex){        }
  //     finally{        } 
   }
   
   /**
    * @param task
    */
   public boolean addTask(jTask task) 
   {
    return taskset.add(task);
   }
   
   /**
    * @param index
    * @return boolean
    */
   public boolean delTask(int index) 
   {
       try{
           taskset.remove(index);
       }
       catch(IndexOutOfBoundsException  e){
           return false;
       }
    return true;
   }
   
   /**
    * @param index
    * @return jTask
    */
   public jTask getTask(int index) 
   {
    return taskset.get(index) ;
   }
   
   /**
    * @param index
    * @param jTask newTask
    * @return boolean
    */
   public boolean updateTask (int index, jTask newTask)
   {
       taskset.set(index,newTask);
    return true;
   }
    public boolean open(String userAccount) throws IOException
   {   
       this.userAccount = userAccount;
       String FileName=userAccount+".Task";
       jFileEditor fe = new jFileEditor(FileName,'r');
  //     if(fe.exists())
       {
           jFileEditor.ReturnType ret = jFileEditor.ReturnType.ok;
          while( true  ){
               ret = fe.startBlock(0,jTask.classMatchCode);
               switch (ret){
                   case ok:
                        jTask tmptask = new jTask();
                        tmptask.readBlockData(fe);
                        taskset.add(tmptask);
                       break;
                   case end:fe=null;return true;
                   default:
                       fe=null;return true;
                       //read a unavailable block head do not match jTask.classMatchCode
                    //   break;
               }
              if(!fe.endBlock())break;
          }
       }
       fe = null;
       return false;
   }
    public boolean flush () throws IOException
   {
       String FileName=userAccount+".Task";
       jFileEditor fe = new jFileEditor(FileName,'w');
 //      if(fe.exists())
       {
           int listSize = taskset.size();
           int i;
           for(i=0; i<listSize; i++){
               jTask tmptask = taskset.get(i);
               fe.startBlock( tmptask.getBlockSize(), jTask.classMatchCode);
               tmptask.writeBlockData(fe);
               if(fe.endBlock() == false)return false;
           }
          return true;
       }
 //       return false;
   }
    
    public int getTotalTaskNum()
   {
       return taskset.size();
   }

}
